/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <types.h>
#include <Signal.h>
#include <time.h>
#include <pthread.h>
#include <ParameterCheck.h>
#include <OSMemory.h>

 typedef struct {
     pthread_cond_t mCond;
     pthread_condattr_t mCondAttr;
     LockType mLock;
 }SignalObjType;

#define SIGNAL_OBJ_TO_SIGNAL_HANDLER(x) (SignalType)(x)
#define SIGNAL_HANDLER_TO_SIGNAL_OBJ(x) (SignalObjType*)(x)


 static uint64_t uptimeMillis() {
     struct timespec now;
     clock_gettime(CLOCK_MONOTONIC, &now);
     uint64_t ns = (((uint64_t) now.tv_sec * 1000000000LL) + now.tv_nsec);
     return ns / 1000000;
 }

 SignalType newSignal() {
    SignalObjType* sig = (SignalObjType*)OS_MALLOC(sizeof(SignalObjType));
    if (!sig) {
        return NULL;
    }

    memset(sig, 0, sizeof(SignalObjType));

    sig->mLock = newLock();
    if (!sig->mLock) {
        OS_FREE(sig);
        return NULL;
    }

    pthread_condattr_init(&sig->mCondAttr);
    pthread_condattr_setclock(&sig->mCondAttr, CLOCK_MONOTONIC);
    pthread_cond_init(&sig->mCond, &sig->mCondAttr);
    return SIGNAL_OBJ_TO_SIGNAL_HANDLER(sig);
}

 void deleteSignal(SignalType sig) {
    SignalObjType* sigObj = SIGNAL_HANDLER_TO_SIGNAL_OBJ(sig);
    PARAMTER_CHECK_RETURN_VOID(sigObj != NULL);
    if (sigObj->mLock) {
        deleteLock(sigObj->mLock);
    }
    pthread_cond_destroy(&sigObj->mCond);
    pthread_condattr_destroy(&sigObj->mCondAttr);
    OS_FREE(sigObj);
 }


void signalWait(SignalType sig, uint32_t timeout) {
    uint64_t timeoutTimestamp = (uptimeMillis() + timeout) * 1000000LL;
    struct timespec timeSpec;
    SignalObjType* sigObj = SIGNAL_HANDLER_TO_SIGNAL_OBJ(sig);
    PARAMTER_CHECK_RETURN_VOID(sigObj != NULL && sigObj->mLock != NULL);

    timeSpec.tv_sec = timeoutTimestamp / 1000000000LL;
    timeSpec.tv_nsec = timeoutTimestamp % 1000000000LL;

    lock(sigObj->mLock);
    pthread_cond_timedwait(&sigObj->mCond, getLockObj(sigObj->mLock), &timeSpec);
    unlock(sigObj->mLock);
}
void setSignal(SignalType sig) {
    SignalObjType* sigObj = SIGNAL_HANDLER_TO_SIGNAL_OBJ(sig);
    PARAMTER_CHECK_RETURN_VOID(sigObj != NULL && sigObj->mLock != NULL);

    lock(sigObj->mLock);
    pthread_cond_signal(&sigObj->mCond);
    unlock(sigObj->mLock);
}

